package com.example.myapplication3.message

import android.R.attr.content
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication3.Msg
import com.example.myapplication3.R

class MessageActivity : AppCompatActivity(), View.OnClickListener {

    private val msgList = ArrayList<Msg>()
    lateinit var msgView: RecyclerView
    lateinit var inputText: EditText
    lateinit var send: Button

    private var adapter: MsgAdapter ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
        msgView = findViewById(R.id.recyclerView_Msg)
        inputText = findViewById(R.id.inputText)
        send = findViewById(R.id.send)
        initMsg()

        val layoutManager = LinearLayoutManager(this)
        msgView.layoutManager = layoutManager
        adapter = MsgAdapter(msgList)
        msgView.adapter = adapter
        send.setOnClickListener(this)

    }
    override fun onClick(v: View?){
        when(v){
            send -> {
                val content = inputText.text.toString()
                if (content.isNotEmpty()){
                    val msg = Msg(content, Msg.TYPE_SENT)
                    msgList.add(msg)
                    adapter?.notifyItemInserted(msgList.size - 1)       // 当有新消息时刷新msgView中的显示
                    msgView.scrollToPosition(msgList.size - 1 )         // 定位到最后一行
                    inputText.setText("")                                         // 清空输入框中的内容
                }
            }
        }
    }
    fun initMsg(){
        val msg1 = Msg("Hello guy.", Msg.TYPE_RECEIVED)
        msgList.add(msg1)

        val msg2 = Msg("Hello, who is that? ", Msg.TYPE_SENT)
        msgList.add(msg2)

        val msg3 = Msg("This is Tom.", Msg.TYPE_RECEIVED)
        msgList.add(msg3)
    }
}